//
//  AccountManageViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "SetGestureLockViewController.h"
#import "AccountManageViewController.h"
#import "CardManageViewController.h"
#import "SecureViewController.h"
#import "LoginPwdViewController.h"
@interface AccountManageViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)UITableView *accountTable;
@property(nonatomic,strong)UISwitch *switchButton;
@property(nonatomic,assign)BOOL isOpen;
@property (nonatomic, strong) NSMutableArray *setDataArray;
@end

@implementation AccountManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    if (!_dataArr) {
        
        
        _dataArr = [[NSMutableArray alloc] initWithCapacity:10];
    }
    [self createUI];
    
    
    
    if(!_setDataArray)
    {
        _setDataArray = [[NSMutableArray alloc]init];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *safeSet = ([[[NSUserDefaults standardUserDefaults]objectForKey:@"idCardVStatus"] isEqualToNumber:[NSNumber numberWithInt:1]]) ? @"已设置" : @"未设置";
    NSString *passwordSet = ([[NSUserDefaults standardUserDefaults]objectForKey:@"password"] != nil) ? @"已设置" : @"未设置";
    [_setDataArray insertObject:safeSet atIndex:0];
    [_setDataArray insertObject:passwordSet atIndex:1];
   
    //每次视图回来的时候，需要判断一次
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"GesturePsd"])
    {
        _isOpen = TRUE;
        [_dataArr removeAllObjects];
        [_dataArr addObjectsFromArray:@[@[@"银行卡管理"],@[@"安全设置",@"登录密码"],@[@"手势密码",@"修改手势密码"]]];
    }else
    {
        _isOpen = FALSE;
        [_dataArr removeAllObjects];
        [_dataArr addObjectsFromArray:@[@[@"银行卡管理"],@[@"安全设置",@"登录密码"],@[@"手势密码"]]];
    }
    if (!_switchButton)
    {
        _switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-100.0f, 7.0f, 40.0f, 20.0f)];
        [_switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    }
    [_switchButton setOn:_isOpen];
    [_accountTable reloadData];
}

-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"账户设置"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];

    [self.view addSubview:topView];
    
    if (!_accountTable)
    {
        _accountTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, topView.frame.size.height+topView.frame.origin.y, SCREEN_WIDTH, SCREEN_HEIGHT-64.0f) style:UITableViewStyleGrouped];
        _accountTable.delegate = self;
        _accountTable.dataSource = self;
        _accountTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _accountTable.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    
        [self.view addSubview:_accountTable];
    }
    
}
#pragma mark--UITableViewDelegate&DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 43.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:sepLab];

        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSArray *array = [self.dataArr objectAtIndex:indexPath.section];
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    NSString * cardStatus = ([[[NSUserDefaults standardUserDefaults]objectForKey:@"cardVStatus"] isEqualToNumber:[NSNumber numberWithInt:1]]) ? @"已设置" : @"未设置";

    if (indexPath.section==0) {
         cell.detailTextLabel.text = cardStatus;
    
    }
    if (indexPath.section==1) {
        if (indexPath.row==0) {
            cell.detailTextLabel.text = [_setDataArray firstObject];


        }
        else{
            cell.detailTextLabel.text = [_setDataArray objectAtIndex:1];

        }
    }
    if (indexPath.section==2) {
        
        if (indexPath.row==0) {
           
            [_switchButton setOn:_isOpen];
            [cell addSubview:_switchButton];
        }
        
    }
    cell.detailTextLabel.textColor = [cell.detailTextLabel.text isEqualToString:@"未设置"]?[UIColor redColor]:[UIColor grayColor];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0)
    {
        if([[[NSUserDefaults standardUserDefaults]objectForKey:@"idCardVStatus"] isEqualToNumber:[NSNumber numberWithInt:1]])
        {
            CardManageViewController *cardVC = [[CardManageViewController alloc] init];
            [self.navigationController pushViewController:cardVC animated:TRUE];
        }
        else
        {
            ALERT_VIEW(@"请到安全设置—>进行实名认证");
        }
    }
    if (indexPath.section==1)
    {
        if (indexPath.row==0)
        {
            SecureViewController *secureVC = [[SecureViewController alloc] init];
            [self.navigationController pushViewController:secureVC animated:TRUE];
        }
        else
        {
            LoginPwdViewController *loginPwdVC = [[LoginPwdViewController alloc] init];
            [self.navigationController pushViewController:loginPwdVC animated:TRUE];
        }
    }
    if (indexPath.section==2)
    {
        if (indexPath.row == 1)
        {
            //进入手势设置界面  #从这个地方进去，是修改密码
            SetGestureLockViewController * vc = [[SetGestureLockViewController alloc]initWithGestureType:reSetGestureLock];
            [self.navigationController pushViewController:vc animated:TRUE];
        }
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.dataArr[section];
    return array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 7.0f;
    }
    else{
        return 40.0f;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

#pragma mark- switch方法
-(void)switchAction:(id)sender
{
    
   NSString *userName = [self secureThePhoneNum:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]];
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
//       开启手势密码
        
        UIAlertView *inputPwdAlt = [[UIAlertView alloc] initWithTitle:@"大大宝账户" message:userName delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        inputPwdAlt.tag = 1000;
        inputPwdAlt.alertViewStyle = UIAlertViewStyleSecureTextInput;
        [inputPwdAlt show];
         }
    else
    {
//     关闭手势密码
        UIAlertView *inputPwdAlt = [[UIAlertView alloc] initWithTitle:@"大大宝账户" message:userName delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        inputPwdAlt.tag = 2000;
        inputPwdAlt.alertViewStyle = UIAlertViewStyleSecureTextInput;
        [inputPwdAlt show];

   
    }
}
#pragma mark-alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1000) {
        switch (buttonIndex) {
            case 0:
            {
                _isOpen = FALSE;
                [_accountTable reloadData];

            }
                
                break;
            case 1:
            {
                
              UITextField *textField = [alertView textFieldAtIndex:0];
                if ([[AppGlobalClass md5:textField.text] isEqualToString:[[NSUserDefaults standardUserDefaults]objectForKey:@"password"]])
                {
                    [_dataArr removeAllObjects];
                    [_dataArr addObjectsFromArray:@[@[@"银行卡管理"],@[@"安全设置",@"登录密码"],@[@"手势密码",@"修改手势密码"]]];
                    _isOpen = TRUE;
                    [_accountTable reloadData];
                     //跳转设置手势界面  #这个时候进去，应该是重新设置
                    [self performSelector:@selector(goToTheSetGestureVc) withObject:nil afterDelay:0.7];

                }else
                {
                    _isOpen = FALSE;
                    ALERT_VIEW(@"密码不正确");
                    [_accountTable reloadData];
                }
            }
                break;
                
            default:
                break;
        }

    }
   else {
        switch (buttonIndex) {
            case 0:
            {
                _isOpen = TRUE;
                [_accountTable reloadData];

            }
                
                break;
            case 1:
            {

                UITextField *textField = [alertView textFieldAtIndex:0];
                
                if ([[AppGlobalClass md5:textField.text] isEqualToString:[[NSUserDefaults standardUserDefaults]objectForKey:@"password"]])
                {
                    [_dataArr removeAllObjects];
                    [_dataArr addObjectsFromArray:@[@[@"银行卡管理"],@[@"安全设置",@"登录密码"],@[@"手势密码"]]];
                    _isOpen = FALSE;
                    [_accountTable reloadData];
                    //删除本地手势密码
                    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"GesturePsd"];
                    
                }else
                {
                    _isOpen = TRUE;
                    ALERT_VIEW(@"密码不正确");
                    [_accountTable reloadData];
                }
            }
                break;
                
            default:
                break;
        }
        
    }

    
}
//给手机号加*号
-(NSString *)secureThePhoneNum:(NSString *)phoneNum
{
    return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}
-(void)goToTheSetGestureVc
{
    SetGestureLockViewController * vc = [[SetGestureLockViewController alloc]initWithGestureType:setGestureLock];
    [self.navigationController pushViewController:vc animated:TRUE];
}
#pragma mark-返回上一页
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
